package com.qixin.modules.eaLoan.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qixin.modules.ea.vo.ListPageVo;
import com.qixin.modules.eaBasic.entity.EaTask;
import com.qixin.modules.eaBasic.mapper.EaTaskMapper;
import com.qixin.modules.eaBasic.vo.EaTaskVo;
import com.qixin.modules.eaBasic.vo.IdVo;
import com.qixin.modules.eaBasic.vo.UserIdPageVo;
import com.qixin.modules.eaLoan.entity.EaLoanbill;
import com.qixin.modules.eaLoan.entity.EaLoanbillDetail;
import com.qixin.modules.eaLoan.entity.EaRepaymentbill;
import com.qixin.modules.eaLoan.mapper.EaLoanbillMapper;
import com.qixin.modules.eaLoan.mapper.EaRepaymentbillMapper;
import com.qixin.modules.eaLoan.service.IEaLoanbillDetailService;
import com.qixin.modules.eaLoan.service.IEaLoanbillService;
import com.qixin.modules.eaLoan.service.IEaRepaymentbillService;
import com.qixin.modules.eaLoan.service.IEaRepaymentbillServiceCopy;
import com.qixin.modules.eaLoan.vo.EaRepaymentbillPage;
import com.qixin.utils.PreciseCompute;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.EmptyUtil;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.activiti.entity.ActZTask;
import org.jeecg.modules.activiti.mapper.ActZTaskMapper;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 还款单
 * @Author: qixin-boot
 * @Date:   2021-07-20
 * @Version: V1.0
 */
@Api(tags="app还款单")
@RestController
@RequestMapping("/app/api/eaRepaymentbill")
@Slf4j
public class ApiEaRepaymentbillController {
    @Autowired
    private IEaRepaymentbillService eaRepaymentbillService;
    @Autowired
    private IEaLoanbillDetailService eaLoanbillDetailService;
    @Autowired
    private INcPersonnelService ncPersonnelService;
    @Autowired
    private EaLoanbillMapper eaLoanbillMapper;
    @Autowired
    private EaRepaymentbillMapper eaRepaymentbillMapper;
    @Autowired
    private ActZTaskMapper actZTaskMapper;

//    /**
//     * 编辑还款单信息
//     *
//     * @param eaRepaymentbillPage
//     * @return
//     */
//    @AutoLog(value = "还款单信息-编辑")
//    @ApiOperation(value="还款单信息-编辑", notes="还款单信息-编辑")
//    @PostMapping(value = "/edit")
//    public Result<?> edit(@RequestBody EaRepaymentbillPage eaRepaymentbillPage) {
//        EaRepaymentbill eaRepaymentbill = new EaRepaymentbill();
//        BeanUtils.copyProperties(eaRepaymentbillPage, eaRepaymentbill);
//        EaRepaymentbill eaRepaymentbillEntity = eaRepaymentbillService.getById(eaRepaymentbill.getId());
//        if(eaRepaymentbillEntity==null) {
//            return Result.error("未找到对应数据");
//        }
//
//        //判断单据是否已经被提交
//        EaRepaymentbill eaRepaymentbill1 = eaRepaymentbillService.getById(eaRepaymentbillPage.getId());
//        String status = EmptyUtil.checkNull(eaRepaymentbill1.getState());   //当状态为1审批中,2已审批时,提示单据状态已变更,请刷新
//        if(status.equals("1") || status.equals("2")){
//            return Result.error("单据状态已变更,请刷新");
//        }
//
//        eaRepaymentbill.setSaveType("add");    //保存
//        Map<String,Object> returnMap = eaRepaymentbillService.updateMain(eaRepaymentbill,eaRepaymentbillPage.getEaLoanbillDetailList());
//
//        if(returnMap.get("code").equals("-1")){
//            return Result.error(EmptyUtil.checkNull(returnMap.get("message")));
//        }else{
//            returnMap.remove("code");
//            returnMap.remove("message");
//            return Result.OK(returnMap);
//        }
//    }

    /**
     *  编辑
     *
     * @param eaRepaymentbillPage
     * @return
     */
    @AutoLog(value = "还款单-编辑")
    @ApiOperation(value="还款单-编辑", notes="还款单-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody EaRepaymentbillPage eaRepaymentbillPage) {
        EaRepaymentbill eaRepaymentbill = new EaRepaymentbill();
        BeanUtils.copyProperties(eaRepaymentbillPage, eaRepaymentbill);
        EaRepaymentbill eaRepaymentbillEntity = eaRepaymentbillService.getById(eaRepaymentbill.getId());
        if(eaRepaymentbillEntity==null) {
            return Result.error("未找到对应数据");
        }
        eaRepaymentbillService.updateMain(eaRepaymentbill, eaRepaymentbillPage.getEaLoanbillDetailList());
        // update-begin-author wjb 2022-02-11 09:16 返回关联的申请单实体
        EaRepaymentbillPage resultPage = new EaRepaymentbillPage();
        BeanUtils.copyProperties(eaRepaymentbill,resultPage);
        // resultPage.setEaLoanbillDetailList(eaRepaymentbillPage.getEaLoanbillDetailList());
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("ea_repaymentbill_id",eaRepaymentbill.getId());
        List<EaLoanbill> eaLoanbills = eaLoanbillMapper.selectByMap(paramsMap);
        // 将冲销金额、当前需还金额、余额返回给前端
        for (EaLoanbill eaLoanbill: eaLoanbills) {
            eaLoanbill.setReveralAmount(eaLoanbill.getLoanAmount());
            eaLoanbill.setCurrentRemainAmount(new BigDecimal(0));
            eaLoanbill.setRemainAmount(new BigDecimal(0));
        }
        List<EaLoanbill> eaLoanbillList = new ArrayList<>();
        eaLoanbillList.addAll(eaLoanbills);
        resultPage.setEaLoanbillDetailList(eaLoanbillList);
        // update-end-author wjb 2022-02-11 09:16 返回关联的申请单实体

        return Result.OK(resultPage);
    }

    /**
     *   添加
     *
     * @param eaRepaymentbillPage
     * @return
     */
    @AutoLog(value = "还款单-添加")
    @ApiOperation(value="还款单-添加", notes="还款单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody EaRepaymentbillPage eaRepaymentbillPage) {
        EaRepaymentbill eaRepaymentbill = new EaRepaymentbill();
        BeanUtils.copyProperties(eaRepaymentbillPage, eaRepaymentbill);
        // update-begin-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("prefix","HK"); // 编码前缀
        Object result = FillRuleUtil.executeRule("common_code", jsonObj);
        eaRepaymentbill.setBillNo(result.toString());
        // update-end-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        eaRepaymentbill.setState(0);
        eaRepaymentbillService.saveMain(eaRepaymentbill, eaRepaymentbillPage.getEaLoanbillDetailList());
        //add-begin-by wjb 2022-02-07 for 返回主表、子表数据给前端
        EaRepaymentbillPage resultPage = new EaRepaymentbillPage();
        BeanUtils.copyProperties(eaRepaymentbill,resultPage);

        // update-begin-author wjb 2022-02-11 09:16 返回关联的申请单实体
        // resultPage.setEaLoanbillDetailList(eaRepaymentbillPage.getEaLoanbillDetailList());
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("ea_repaymentbill_id",eaRepaymentbill.getId());
        List<EaLoanbill> eaLoanbills = eaLoanbillMapper.selectByMap(paramsMap);
        // 将冲销金额、当前需还金额、余额返回给前端
        for (EaLoanbill eaLoanbill: eaLoanbills) {
            eaLoanbill.setReveralAmount(eaLoanbill.getLoanAmount());
            eaLoanbill.setCurrentRemainAmount(new BigDecimal(0));
            eaLoanbill.setRemainAmount(new BigDecimal(0));
        }
        List<EaLoanbill> eaLoanbillList = new ArrayList<>();
        eaLoanbillList.addAll(eaLoanbills);
        resultPage.setEaLoanbillDetailList(eaLoanbillList);
        // update-end-author wjb 2022-02-11 09:16 返回关联的申请单实体

        //add-end-by wjb 2022-02-07 for 返回主表、子表数据给前端
        return Result.OK(resultPage);
    }

//    /**
//     * 查询还款单信息列表
//     *
//     * @param listPageVo
//     * @return Result
//     */
//    @ApiOperation(value="还款单信息列表-查询", notes="还款单信息列表-查询")
//    @PostMapping(value = "/list")
//    public Result<?> list(@RequestBody ListPageVo listPageVo) {
//        Map<String,Object> resutlList = eaRepaymentbillService.list(listPageVo);
//        return Result.OK(resutlList);
//    }

    /**
     * 分页列表查询
     *
     * @param eaRepaymentbill
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value="还款单-分页列表查询", notes="还款单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(EaRepaymentbill eaRepaymentbill,
                                   @RequestParam(name="billDateBegin", required = false) String billDateBegin,
                                   @RequestParam(name="billDateEnd", required = false) String billDateEnd,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   @RequestParam(name = "billCode", required = false) String billCode,
                                   HttpServletRequest req) {
        QueryWrapper<EaRepaymentbill> queryWrapper = QueryGenerator.initQueryWrapper(eaRepaymentbill, req.getParameterMap());
        //add-begin-by wujinbiao for 添加查询条件 列表排序，创建人
        if (org.apache.commons.lang3.StringUtils.isNotBlank(billDateBegin)){
            queryWrapper.ge("bill_date", billDateBegin);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(billDateEnd)){
            queryWrapper.le("bill_date", billDateEnd);
        }
        if(org.apache.commons.lang3.StringUtils.isNotBlank(billCode)){
            // 单据编号模糊查询
            queryWrapper.like("bill_no",billCode);
        }
        queryWrapper.orderByDesc("create_time");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.eq("create_by",loginUser.getId());
        //add-end-by wujinbiao for 添加查询条件
        Page<EaRepaymentbill> page = new Page<EaRepaymentbill>(pageNo, pageSize);
        IPage<EaRepaymentbill> pageList = eaRepaymentbillService.page(page, queryWrapper);
        List<EaRepaymentbill> records = pageList.getRecords();
        for (EaRepaymentbill eaRepaymentbill1:records) {
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaRepaymentbill1.getPersonId());
            if(ncPersonnel != null){
                eaRepaymentbill1.setPersonIdName(ncPersonnel.getName());
            }
        }
        return Result.OK(pageList);
    }

//    /**
//     * 查询还款单详情
//     *
//     * @param idVo
//     * @return
//     */
//    @ApiOperation(value="还款单详情-查询", notes="还款单详情-查询")
//    @PostMapping(value = "/selectById")
//    public Result<?> selectById(@RequestBody IdVo idVo) {
//        String id = idVo.getId();
//        EaRepaymentbill eaRepaymentbill = eaRepaymentbillMapper.selectById(id);
//        if(eaRepaymentbill==null) {
//            return Result.error("未找到对应数据");
//        }
//        Map<String, Object> resutlList = eaRepaymentbillService.selectById(id);
//        return Result.OK(resutlList);
//    }

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @ApiOperation(value="还款单-通过id查询", notes="还款单-通过id查询")
    @GetMapping(value = "/selectById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
        EaRepaymentbill eaRepaymentbill = eaRepaymentbillService.getById(id);
        if(eaRepaymentbill==null) {
            return Result.error("未找到对应数据");
        }
        // 返回还款人中文
        if(org.apache.commons.lang3.StringUtils.isNotBlank(eaRepaymentbill.getPersonId())){
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaRepaymentbill.getPersonId());
            if (ncPersonnel != null){
                eaRepaymentbill.setPersonIdName(ncPersonnel.getName());
            }
        }
        // update-begin-author wjb 2022-02-11 09:16 返回关联的申请单实体

//		//查询子表数据
//		List<EaLoanbillDetail> eaLoanbillDetails = eaLoanbillDetailService.selectByMainId(eaRepaymentbill.getId());
//		eaRepaymentbillPage.setEaLoanbillDetailList(eaLoanbillDetails);

        EaRepaymentbillPage resultPage = new EaRepaymentbillPage();
        BeanUtils.copyProperties(eaRepaymentbill,resultPage);
        // resultPage.setEaLoanbillDetailList(eaRepaymentbillPage.getEaLoanbillDetailList());
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("ea_repaymentbill_id",eaRepaymentbill.getId());
        List<EaLoanbill> eaLoanbills = eaLoanbillMapper.selectByMap(paramsMap);
        // 将冲销金额、当前需还金额、余额返回给前端
        for (EaLoanbill eaLoanbill: eaLoanbills) {
            eaLoanbill.setReveralAmount(eaLoanbill.getLoanAmount());
            eaLoanbill.setCurrentRemainAmount(new BigDecimal(0));
            eaLoanbill.setRemainAmount(new BigDecimal(0));
        }
        List<EaLoanbill> eaLoanbillList = new ArrayList<>();
        eaLoanbillList.addAll(eaLoanbills);
        resultPage.setEaLoanbillDetailList(eaLoanbillList);
        // update-end-author wjb 2022-02-11 09:16 返回关联的申请单实体

        return Result.OK(resultPage);

    }

//    /**
//     * 通过id删除还款单
//     *
//     * @param idVo
//     * @return
//     */
//    @AutoLog(value = "还款单信息-通过id删除")
//    @ApiOperation(value="还款单信息-通过id删除", notes="还款单信息-通过id删除")
//    @PostMapping(value = "/delete")
//    public Result<?> delete(@RequestBody IdVo idVo) {
//        eaRepaymentbillService.delMain(idVo.getId());
//        return Result.OK("删除成功!");
//    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "还款单-通过id删除")
    @ApiOperation(value="还款单-通过id删除", notes="还款单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        QueryWrapper<EaRepaymentbill> params = new QueryWrapper<>();
        params.eq("id",id);
        EaRepaymentbill eaRepaymentbill = eaRepaymentbillService.getOne(params);
        if (eaRepaymentbill != null && eaRepaymentbill.getState()>0){
            return Result.error("该单据已发起流程,不可删除!");
        }
        eaRepaymentbillService.delMain(id);
        return Result.OK("删除成功!");
    }

//    /**
//     * 还款单审批/退回
//     *
//     * @param eaTaskVo
//     * @return
//     */
//    @AutoLog(value = "还款单审批/退回")
//    @ApiOperation(value="还款单审批/退回", notes="还款单审批/退回")
//    @PostMapping(value = "/audit")
//    public Result<?> edit(@RequestBody EaTaskVo eaTaskVo) {
//        Map<String,Object> returnMap = eaRepaymentbillService.audit(eaTaskVo);
//        return Result.OK(returnMap);
//    }

//    /**
//     * description:
//     * create time: 2021/12/24 9:52
//     * create by: wjb
//     * @params billId
//     * @return
//     */
//    @AutoLog(value = "还款单状态更新")
//    @ApiOperation(value="还款单状态更新", notes="还款单状态更新")
//    @PutMapping(value = "/updateLoanBillState")
//    public Result<?> updateLoanBillState(@RequestParam(name="billIds",required=true) String billIds){
//        if (!StringUtils.isEmpty(billIds)) {
//            String[] ids = billIds.split(",");
//            // 借款金额
//            double loanAmount = 0;
//            // 业务表id
//            String billId = "";
//            List<EaLoanbillDetail> eaLoanbillDetails = new ArrayList<>();
//            List<EaLoanbill> loanbills = new ArrayList<>();
//            for (String id : ids) {
//                EaLoanbillDetail eaLoanbillDetail = eaLoanbillDetailService.selectById(id);
//                // 查询借款单
//                EaLoanbill loanbill = loanbillService.getById(eaLoanbillDetail.getEaLoanbillId());
//                // 还款单id
//                billId = eaLoanbillDetail.getEaRepaymentbillId();
//                // 发票被引用
//                if ("1".equals(loanbill.getIsused()) && eaLoanbillDetail.getEaRepaymentbillId() != null) {
//                    loanAmount = PreciseCompute.add(loanAmount,eaLoanbillDetail.getLoanBillAmount().doubleValue());
//                    // 关联的表单id置为空
//                    eaLoanbillDetail.setEaRepaymentbillId("");
//                    // 发票状态更新
//                    loanbill.setIsused("0");
//
//                    eaLoanbillDetails.add(eaLoanbillDetail);
//                    loanbills.add(loanbill);
//                }
//            }
//            eaLoanbillDetailService.updateBatchById(eaLoanbillDetails);
//            loanbillService.updateBatchById(loanbills);
//
//            // 报销单减去实际付款金额、报销金额
//            if (billId != ""){
//                EaRepaymentbill eaRepaymentbill = eaRepaymentbillService.queryById(billId);
//                // 修改待办列表的还款金额
//                Map<String, Object> params = new HashMap<>();
//                params.put("form_id",billId);
//                List<EaTask> eaTasks = eaTaskMapper.selectByMap(params);
//                if(eaTasks.size() > 0){
//                    // 修改任务列表 对应的借款金额
//                    EaTask eaTask = eaTasks.get(0);
//                    eaTask.setTotalFee(new BigDecimal(PreciseCompute.sub(eaRepaymentbill.getRepaymentAmount().doubleValue(),loanAmount)));
//                    eaTaskMapper.updateById(eaTask);
//                }
//                // 差旅费报销单 报销金额 修改
//                eaRepaymentbill.setRepaymentAmount(new BigDecimal(PreciseCompute.sub(eaRepaymentbill.getRepaymentAmount().doubleValue(),loanAmount)));
//                eaRepaymentbillService.updateById(eaRepaymentbill);
//
//            }
//        }
//        return Result.OK();
//    }

    /**
     * description:
     * create time: 2021/12/24 9:52
     * create by: wjb
     * @params billId
     * @return
     */
    @AutoLog(value = "还款单状态更新")
    @ApiOperation(value="还款单状态更新", notes="还款单状态更新")
    @PutMapping(value = "/updateLoanBillState")
    public Result<?> updateLoanBillState(@RequestParam(name="billIds",required=true) String billIds){
        if (org.apache.commons.lang3.StringUtils.isNotBlank(billIds)) {
            String[] ids = billIds.split(",");
            // 还款单id
            String eaRepaymentbillId = "";
            // 借款金额
            double loanAmount = 0;
            if(ids.length > 0){
                for (String id:ids) {
                    // 获取借款单信息
                    EaLoanbill eaLoanbill = eaLoanbillMapper.selectById(id);
                    eaRepaymentbillId = eaLoanbill.getEaRepaymentbillId();
                    if(eaLoanbill != null && eaLoanbill.getEaRepaymentbillId() != null){
                        // 取消借款单的使用标识
                        eaLoanbillMapper.updateByBillId(id);
                        // 获取借款金额
                        loanAmount = PreciseCompute.add(loanAmount,eaLoanbill.getLoanAmount().doubleValue());
                    }
                }
            }
            if(ids.length > 0){
                if (StringUtils.isNotBlank(eaRepaymentbillId)){
                    // 还款单表单数据修改
                    EaRepaymentbill eaRepaymentbill = eaRepaymentbillMapper.selectById(eaRepaymentbillId);
                    eaRepaymentbill.setRepaymentAmount(new BigDecimal(PreciseCompute.sub(eaRepaymentbill.getRepaymentAmount().doubleValue(),loanAmount)));
                    eaRepaymentbillService.updateById(eaRepaymentbill);
                }
            }
            // 代办任务修改
            // 修改待办列表的还款金额
            EaRepaymentbill eaRepaymentbill = eaRepaymentbillMapper.selectById(eaRepaymentbillId);
            Map<String, Object> params = new HashMap<>();
            params.put("table_id",eaRepaymentbillId);
            List<ActZTask> actZTasks = actZTaskMapper.selectByMap(params);
            if(actZTasks.size() > 0){
                // 修改任务列表 对应的借款金额
                ActZTask actZTask = actZTasks.get(0);
                actZTask.setTotalFee(eaRepaymentbill.getRepaymentAmount());
                actZTaskMapper.updateById(actZTask);
            }
        }
        return Result.OK();
    }
}
